package com.tecnap.app.activity;

import com.tecnap.R;
import com.tecnap.app.LampEntity;
import com.tecnap.app.database.LampDataSource;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class FormActivity extends Activity {

	// GPS Status
	private boolean gpsStatus = false;

	// ID of the lamp loaded from an intent
	// see: com.tecnap.app.activity.DataActivity
	private int lampID = 0;

	// Latitude and Longitude
	Double lat = 0.0;
	Double lon = 0.0;
	Double alt = 0.0; // Altitude
	Float pre = new Float(0.0); // Accuracy

	// Object lamp
	private LampEntity lamp;

	// Connector for db table "lamp"
	private LampDataSource lampDataSource;

	// List of Lamp Type shown in Spinner
	private static final String[] lampTypes = { "SAP", "Ioduri metallici",
			"Fluorescenza", "Vapori di mercurio", "SBP", "Altro" };

	// List of Lamp Power shown in Spinner
	private static final String[] lampPowers = { "70W", "100W", "150W", "250W",
			"400W", "Altro" };

	// Types and Power Adapter
	private ArrayAdapter<CharSequence> lampTypesAdapter;
	private ArrayAdapter<CharSequence> lampPowersAdapter;

	// Location listener and location manager
	LocationListener locationListener;
	LocationManager locationManager;

	// The UI Components
	EditText lampNumber;
	EditText lampBrand;
	EditText lampModel;
	EditText lampComment;
	Spinner lampPower;
	Spinner lampType;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.form);

		// Retrieve all UI Components
		lampNumber = (EditText) findViewById(R.id.lampNumberEdit);
		lampBrand = (EditText) findViewById(R.id.lampBrandEdit);
		lampModel = (EditText) findViewById(R.id.lampModelEdit);
		lampComment = (EditText) findViewById(R.id.lampCommentEdit);
		lampPower = (Spinner) findViewById(R.id.lampPowerEdit);
		lampType = (Spinner) findViewById(R.id.lampTypeEdit);

		// Lamp Type and Power Spinners
		lampTypesAdapter = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item, lampTypes);
		lampTypesAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		lampType.setAdapter(lampTypesAdapter);

		lampPowersAdapter = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item, lampPowers);
		lampPowersAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		lampPower.setAdapter(lampPowersAdapter);

		// Database table "lamp" Connector
		lampDataSource = new LampDataSource(this);

		// GPS

		// Acquire a reference to the system Location Manager
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		// Define a listener that responds to location updates
		locationListener = new LocationListener() {
			TextView lampPositionEdit = (TextView) findViewById(R.id.lampPositionEdit);

			public void onLocationChanged(Location location) {
				// Called when a new location is found by the network location
				// provider.
				lat = location.getLatitude();
				lon = location.getLongitude();
				alt = location.getAltitude();
				pre = location.getAccuracy();
				String preString = "";
				if (pre.toString().length() > 5) {
					preString = pre.toString().substring(0, 5);
				} else {
					preString = pre.toString();
				}
				lampPositionEdit.setText("Lat: "
						+ lat.toString().substring(0, 7) + ", Lon: "
						+ lon.toString().substring(0, 7) + ", Alt: "
						+ alt.toString().substring(0, 5) + "m, Prec: "
						+ preString + "m");
				gpsStatus = true;
			}

			public void onStatusChanged(String provider, int status,
					Bundle extras) {
			}

			public void onProviderEnabled(String provider) {
				lampPositionEdit.setText("Rilevamento posizione in corso ...");
				gpsStatus = false;
			}

			public void onProviderDisabled(String provider) {
				lampPositionEdit.setText("GPS Spento!");
				gpsStatus = false;
			}
		};

		// Register the listener with the Location Manager to receive location
		// updates
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
				0, locationListener);
	}

	@Override
	public void onResume() {
		super.onResume();

		// Open connection to Database
		lampDataSource.open();

		/**
		 * Check if there is some Lamp to edit
		 */
		MainActivity parent = (MainActivity) getParent();

		String number = parent.getExtra("lampNumber");

		if (number != null) {
			lamp = lampDataSource.getLampByNumber(number);
			fillForm(lamp);
		}
	}

	@Override
	public void onPause() {
		super.onPause();

		// Open connection to Database
		lampDataSource.close();
	}

	/**
	 * Called on onClick event of button addLamp
	 * 
	 * @param v
	 * @throws Exception
	 */
	public void addLamp(View v) {

		if (!lampNumber.getText().toString().equals("") && gpsStatus == true) {
			// Messaggio di default visualizzato nella dialog
			String message = "Lampada salvata correttamente!";

			try {
				// Verify
				LampEntity existingLamp = lampDataSource.getLampByNumber(lampNumber.getEditableText().toString());
				if (existingLamp != null && lampID == 0) {
					// Error! Existing Lamp!!!
					AlertDialog dialog = new AlertDialog.Builder(this).create();
					dialog.setMessage("ERRORE! Una lampada con questo numero già esiste!\nImpossibile salvare");
					dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,	int which) {
									dialog.dismiss();
								}
							});
					dialog.show();

				} else {  
					// Initialize a new lamp object
					lamp = new LampEntity(lampID,
							lampNumber.getEditableText().toString(),
							lampType.getSelectedItem().toString(),
							lampBrand.getEditableText().toString(),
							lampPower.getSelectedItem().toString(),
							lampModel.getEditableText().toString(),
							lampComment.getEditableText().toString(),
							lat.floatValue(),
							lon.floatValue());

					// Save or modify lamp into db
					lampDataSource.setLamp(lamp);
					// Show alertDialog
					AlertDialog dialog = new AlertDialog.Builder(this).create();
					dialog.setMessage(message);
					dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
								}
							});
					dialog.show();

					// Clear fields of the form
					resetAllFields();
				}
			} catch (Exception e) {
				message = e.getMessage();
				// Show alertDialog
				AlertDialog dialog = new AlertDialog.Builder(this).create();
				dialog.setMessage("ERRORE: " + message);
				dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
				dialog.show();
			}

			
		} else if (!gpsStatus == true) {
			// GPS OFF, Can't save. Show alertDialog
			AlertDialog dialog = new AlertDialog.Builder(this).create();
			dialog.setMessage("GPS non attivo, impossibile salvare!\naccendere il GPS, attendere il recupero della posizione e riprovare.");
			dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			dialog.show();
		} else if (lampNumber.getText().toString().equals("")) {
			// GPS OFF, Can't save. Show alertDialog
			AlertDialog dialog = new AlertDialog.Builder(this).create();
			dialog.setMessage("Numero lampada vuoto!\nSpecificare il numero lampada.");
			dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			dialog.show();
		}
	}

	/**
	 * Called on onClick event of button deleteLamp
	 * 
	 * @param v
	 */
	public void deleteLamp(View v) {
		if (lamp == null)
			return;

		AlertDialog dialog = new AlertDialog.Builder(this).create();
		dialog.setMessage("Cancellare Lampada N°: " + lamp.getNumber() + " ?");
		dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Si",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (lampDataSource.removeLampByNumber(lamp.getNumber())) {
							resetAllFields();
						}
						dialog.dismiss();
					}
				});
		dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "No",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		dialog.show();
	}

	/**
	 * Called on onClick event of button resetLamp
	 * 
	 * @param v
	 */
	public void confirmResetAllFields(View v) {
		AlertDialog dialog = new AlertDialog.Builder(this).create();
		dialog.setMessage("Pulire i campi del modulo ?");
		dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Si",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						resetAllFields();
						dialog.dismiss();
					}
				});
		dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "No",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		dialog.show();
	}

	/**
	 * This method automatically fill the fields of the form using a lamp object
	 * 
	 * @param lamp
	 */
	private void fillForm(LampEntity lamp) {
		if (lamp == null)
			return;

		lampID = lamp.getID();

		lampNumber.setText(lamp.getNumber());
		lampBrand.setText(lamp.getBrand());
		lampModel.setText(lamp.getModel());
		lampComment.setText(lamp.getComment());

		// Default lampTypeSpinner selection
		for (int i = 0; i < lampTypes.length; i++) {
			if (lampTypes[i].equals(lamp.getType())) {
				lampType.setSelection(i);
				break;
			}
		}

		// Default lampPowerSpinner selection
		for (int i = 0; i < lampPowers.length; i++) {
			if (lampPowers[i].equals(lamp.getPower())) {
				lampPower.setSelection(i);
				break;
			}
		}

		lat = (double) lamp.getPositionX();
		lon = (double) lamp.getPositionY();
	}

	/**
	 * This method is used to clear all fields of the form
	 */
	private void resetAllFields() {
		// Reset to null all fields of the form
		lamp = null;
		lampID = 0;

		lampNumber.setText("");
		lampType.setSelection(0);
		lampBrand.setText("");
		lampPower.setSelection(0);
		lampModel.setText("");
		lampComment.setText("");
	}
}
